package com.example.shopping_web_back.controller;

import com.example.shopping_web_back.pojo.Result;
import com.example.shopping_web_back.pojo.ShoppingCar;
import com.example.shopping_web_back.service.ShoppingCarService;
import com.example.shopping_web_back.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ShoppingCar")
@Validated
public class ShoppingCarController {

    @Autowired
    private ShoppingCarService shoppingCarService;

    //查看购物车
    @GetMapping("/gotData")
    public Result<List<ShoppingCar>> list() {
        List<ShoppingCar> pbShoppingCar = shoppingCarService.list();
        return Result.success(pbShoppingCar);
    }

    //向购物车添加商品
    @PostMapping("addGoods")
    public Result addGoods(@RequestHeader(name = "Customer") String token,@RequestBody ShoppingCar shoppingCar) {
        System.out.println(shoppingCar);
        ShoppingCar checkShoppingCar = shoppingCarService.findGoods(shoppingCar);
        if(checkShoppingCar == null) {
            //如果购物车没有这个商品，则加入
            shoppingCarService.addGoods(shoppingCar);
            return Result.success();
        }
        //如果有，那就更新数量
        shoppingCarService.updateGoods(shoppingCar, checkShoppingCar.getGoodsNum() + shoppingCar.getGoodsNum(), checkShoppingCar.getIsPurchase());
        return Result.success();
    }

    //修改购物车中商品数据
    @PostMapping("/updateShoppingCar")
    public Result updateGoods(@RequestHeader(name = "Customer") String token,@RequestBody ShoppingCar shoppingCar) {
        shoppingCarService.updateGoods(shoppingCar, shoppingCar.getGoodsNum(), shoppingCar.getIsPurchase());
        return Result.success();
    }

    //删除购物车中的某个商品
    @PostMapping("/deleteGoods")
    public Result deleteGoods(@RequestHeader(name = "Customer") String token,@RequestBody Map<String, String> params) {
        ShoppingCar shoppingCar = new ShoppingCar();
        Map<String, Object> map = ThreadLocalUtil.get(); //先得到用户
        String customerName = (String)map.get("customer_name");
        shoppingCar.setCustomerName(customerName);
        shoppingCar.setGoodsName(params.get("goods_name"));
        shoppingCar.setBusinessName(params.get("business_name"));
        shoppingCarService.deleteGoods(shoppingCar);
        return Result.success();
    }
}
